import { createContext } from "react";
import actions from "./actions";
export const initialTasks = {
  count: 0,
  loading: false,
};
export const TasksContext = createContext(initialTasks);

const deconstructionActionType = (type) => {
  if (!type) {
    return null;
  }
  if (typeof type !== "string") {
    return null;
  }
  if (!type.includes(".")) {
    return null;
  }
  const [parentKey, reducerKey] = type.split(".");
  return {
    parentKey,
    reducerKey,
  };
};

export const tasksReducer = (state, action) => {
  const keys = deconstructionActionType(action.type);
  if (keys !== null) {
    const { parentKey, reducerKey } = keys;
    if (
      typeof actions[parentKey] === "object" &&
      typeof actions[parentKey].reducer === "object" &&
      typeof actions[parentKey].reducer[reducerKey] === "function"
    ) {
      return actions[parentKey].reducer[reducerKey](state, action);
    }
  }
};

export const buildDispatch = (dispatch) => {
  const buildActions = {};
  const parentKeys = Object.keys(actions);

  const dealWithItemActions = (parentKey) => {
    const item = actions[parentKey];
    const itemActionKeys = Object.keys(item.actions);
    for (let index = 0; index < itemActionKeys.length; index++) {
      const actionKey = itemActionKeys[index];
      if (typeof item.actions[actionKey] === "function") {
        buildActions[parentKey][actionKey] = (...args) => {
          dispatch(item.actions[actionKey](...args));
        };
      }
    }
  };

  for (let index = 0; index < parentKeys.length; index++) {
    const parentKey = parentKeys[index];
    if (typeof actions[parentKey].actions === "object") {
      !buildActions[parentKey] && (buildActions[parentKey] = {});
      dealWithItemActions(parentKey);
    }
  }
  return buildActions;
};
